package com.nuorui.module.system.manager;


import cn.hutool.core.collection.CollectionUtil;
import com.nuorui.module.system.mapper.RoleUserMapper;
import com.nuorui.module.system.mapper.UserMapper;
import com.nuorui.module.system.domain.entity.RoleUserEntity;
import com.nuorui.module.system.domain.entity.UserEntity;
import com.nuorui.module.system.service.RoleUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工 manager
 *
 * @Author 1024创新实验室: 胡克
 * @Date 2021-12-29 21:52:46
 * @Wechat zhuoda1024
 * @Email lab1024@163.com
 * @Copyright  <a href="https://1024lab.net">1024创新实验室</a>
 */
@Service
public class UserManager  {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleUserService roleUserService;

    @Resource
    private RoleUserMapper roleUserMapper;

    /**
     * 保存员工
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(UserEntity entity, List<Long> roleIdList) {
        // 保存数据
        userMapper.insert(entity);
        if (CollectionUtil.isNotEmpty(roleIdList)) {
            List<RoleUserEntity> roleUserList = roleIdList.stream().map(e -> new RoleUserEntity(e, entity.getUserId())).collect(Collectors.toList());
            roleUserService.saveBatch(roleUserList);
        }
    }

    /**
     * 更新员工
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserEntity entity, List<Long> roleIdList) {
        // 保存员工 获得id
        userMapper.updateById(entity);

        // 若为空，则删除所有角色
        if (CollectionUtil.isEmpty(roleIdList)) {
            roleUserMapper.deleteByUserId(entity.getUserId());
            return;
        }

        List<RoleUserEntity> roleUserList = roleIdList.stream().map(e -> new RoleUserEntity(e, entity.getUserId())).collect(Collectors.toList());
        updateUserRole(entity.getUserId(), roleUserList);
    }

    /**
     * 更新员工角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserRole(Long userId, List<RoleUserEntity> roleUserList) {
        roleUserMapper.deleteByUserId(userId);
        if (CollectionUtil.isNotEmpty(roleUserList)) {
            roleUserService.saveBatch(roleUserList);
        }
    }

}
